<template>
<div class="extend-con">
    <el-dialog title="批量卡券发放" :visible.sync="extendData.dialogExtend"  :before-close="handleClose">
        <el-form label-width="90px" class="demo-ruleForm formstyle" :rules="rules" label-position="right" :model="ruleForm" ref="ruleForm">
            <el-row :gutter="21">
                <el-col :span="8">
                    <el-form-item label="家长手机号" prop="phone">
                        <el-input v-model="ruleForm.phone" placeholder="请输入家长手机号" :maxlength="11"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="学生姓名" prop="studentName">
                        <el-input v-model="ruleForm.studentName" placeholder="请输入学生姓名" :maxlength="12"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-button type="primary" style="float:right" @click="searchData('ruleForm')">查询</el-button>
                </el-col>          
            </el-row>
        </el-form>
        <div class="extend-cen">
            <el-row :gutter="21">
                <el-col :span="8">
                    <div class="extend-class-left">
                        <div class="extend-title">选择班级</div>
                        <ul>
                            <li v-for="(item, index) in classList" 
                            @click="setActive(index, item)" 
                            :class="{active:leftIndex == index}" :key="index" >{{item.sNickName}}&nbsp;&nbsp;<span v-if="item.num">(已选：{{item.num}}人)</span></li>
                        </ul>
                    </div>
                </el-col>
                <el-col :span="16">
                    <div class="extend-class-right">
                        <el-table :data="tableData" style="width: 100%; border:1px solid #ddd;"  height="320"  @selection-change="handleSelectionChange" 
                            :key="leftIndex" ref="multipleTable">                           
                            <el-table-column label="家长姓名" align="left"  prop="parentName" ></el-table-column>
                            <el-table-column label="手机号" align="left" prop="parentPhone" ></el-table-column>
                            <el-table-column label="学生姓名" align="left" prop="studentName" ></el-table-column> 
                            <el-table-column label="家属关系" align="left" prop="relationName" ></el-table-column>
                            <el-table-column type="selection" width="55"></el-table-column>
                        </el-table>
                    </div>
                </el-col>   
            </el-row>
            <!-- {{statusData.length}} -->
            <el-row :gutter="21" style="margin-top:22px; margin-bottom:22px;" v-show="statusData.length>1">
                <el-col :span="8" style="display:flex; ">
                    <div style="width:120px; line-height:36px;"><b style="color:#f00; padding:0 5px;">*</b>开通时长</div>
                    <el-select v-model="timeStatus" placeholder="请选择" style="width:100%" v-autoResize @change="getCardNum">
                        <el-option v-for="(item,index) in statusData" :key="index" 
                        :label="item.usefullifename" 
                        :value="item.usefullife"> 
                        </el-option>
                    </el-select>
                </el-col>
                <el-col v-if="timeStatus" :span="8" style="line-height:36px;">卡券数量{{cradNum}}张</el-col>    
            </el-row>          
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="extendData.dialogExtend = false">取 消</el-button>
            <el-button type="primary" @click="extendCard" :loading="loadingBtn">确 定</el-button>
        </div>
    </el-dialog>  
</div>
</template>
<script>
import { mapGetters } from 'vuex';
import {listClassInfoBySchoolId, listFamilyRelation, saveCardGrant, listOpenTimeData, getCardNotGrantNums} from 'api/cardCoupons'
import validate from '@/utils/validate';
export default {
    props: {
        extendData: {
            default() {
                return {
                    dialogExtend: false // 默认不显示!
                }
            },
            required: true
        }
    },
    data() {
        return {
            ruleForm: {
                studentName: '',               
                phone: '',
                pid: ''// 激活状态的班级id
            },
            statusData: [],
            cradNum: 0,
            timeStatus: null,
            leftIndex: null,
            classList: [], // 班级列表
            loadingBtn: false,
            tableData: [],
            multipleSelection: [],
            newSelection: [],
            rules: {
                leaderName: [
                    { required: true, message: '请输入负责人姓名', trigger: 'blur' }
                ],
                phone: [...validate.phone()]
            }
        }
    },
    computed: {
        ...mapGetters([
            'uid'
        ])
    },
    watch: {
        'extendData.dialogExtend'(val) {
            if (val) {
                this.newSelection = [];
                this.multipleSelection = [];
                this.classList = [];
                this.tableData = [];
                this.leftIndex=null;
                this.getClasslist();
            }
        }
    },
    created() {
        this.getOpenTimeList();// 获取开通时长下拉信息
    },
    methods: {
        // 确定发放
        extendCard(formName) {
            // 如果只存在一种开通时长,不显示下拉选择框，并且点击确认时，发送默认的该开通时长
            if (!this.statusData.length) {// 没有开通时长
                this.$message.error('没有开通时长，暂不能发放卡券！');
                return
            } else if (this.statusData.length>1) {// 多种开通时长
                if (!this.timeStatus) {// 不选择
                    this.$message.error('请选择开通时长！');
                    return
                }
            }
            if (this.newSelection.length) {
                let inforMag='确认将卡券发放吗？';
                this.$confirm(inforMag, ' ', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                    this.sendCard(); // 发放
                }).catch(() => {
                    this.$message.info('已取消');  
                });
            } else {
                this.$alert('请选择需要发放的用户后再点击发放!', ' ', {
                    confirmButtonText: '取消',
                    callback: action => {
                        this.$message.info('已取消');
                    }
                });
            }
        },
        // 批量发放
        sendCard() {
            this.loadingBtn=true;
            let grantUserId=[];// 家长id数组
            let grantUserName=[];// 家长名字数组
            let grantClassId=[];// 班级id数组
            let grantCalssName=[];// 班级名字数组
            let schoolId=this.extendData.schoolId;
            let schoolName=this.extendData.schoolName;
            let serviceId=this.extendData.serviceId;
            let serviceName=this.extendData.serviceName;
            let orgUserId='';// 经销商的
            let orgUserName='';
            let pId='';
            this.newSelection.forEach((val, index) => {
                val.newMultiple.forEach((vals) => {
                    grantUserId.push(vals.parentUserId);
                    grantUserName.push(vals.parentName);
                    grantClassId.push(vals.classId);
                    grantCalssName.push(vals.className);
                })
            });
            // debugger
            saveCardGrant(
                grantUserId,
                grantUserName,
                grantClassId,
                grantCalssName,
                schoolId,
                schoolName,
                serviceId,
                serviceName,
                orgUserId,
                orgUserName,
                pId,
                this.timeStatus
            ).then(res => {
                this.loadingBtn=false;
                this.$message.success('卡券发放成功！')
                this.queryFarData();
                this.clearData();
            }).catch(() => {
                this.loadingBtn=false
            });
        },
        queryFarData() {
            this.$emit('queryData');
            this.$emit('getCardNums'); // 2018-01-10 by cuihd
        },
        
        getOpenTimeList() {
            listOpenTimeData(this.$route.params.schoolId, this.extendData.serviceId).then(res => {
                // 如果只有一种开通时长，把id取出来赋值给 this.timeStatus，保证点击确认时直接发送
                if (res.data.content.length==1) {// 只有一种开通时长，就不给下拉框赋值，不显示下拉框
                    this.timeStatus=res.data.content[0].usefullife// 把id取出来赋值给 this.timeStatus，保证点击确认时直接发送
                }
                if (res.data.content.length>1) {
                    this.timeStatus='';
                }
                this.statusData = res.data.content;
            })
        },

        getCardNum() {
            if (!this.timeStatus) return;        
            getCardNotGrantNums(this.extendData.schoolId, this.extendData.serviceId, this.timeStatus).then(res => {
                this.cradNum = res.data.content.cardNums;
            })
        },
        // 勾选右侧关系时
        handleSelectionChange(val) {
            this.$set(this.classList[this.leftIndex], 'num', val.length);
            this.multipleSelection = val;
            this.newSelection.map(item => {
                if (item.classId == this.ruleForm.pid) {
                    item.newMultiple = this.multipleSelection;
                }
            });
            // console.log(JSON.stringify(this.newSelection, null, 4), '+++++++++++++++', val)
        },
        // 点击某个班级
        setActive(index, item) {
            this.leftIndex = index;
            this.ruleForm.pid = item.pId; // 班级的id
            this.getListFamily(this.ruleForm.pid);          
        },
        searchData(ruleForm) {
            if (!this.ruleForm.pid) {
                this.$message.error('请先选择班级再查询家长学生关系信息哟！');
                return
            }
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    this.getListFamily(this.ruleForm.pid, this.ruleForm.phone, this.ruleForm.studentName);
                } else {
                    return false;
                }
            });
        },   
        // 卡券发放家长学生信息
        getListFamily(pid, phone, studentName) {
            listFamilyRelation(pid, phone, studentName).then(res => {
                this.tableData = res.data.content;
                JSON.parse(JSON.stringify(this.newSelection)).map(item => {
                    if (item.classId == pid) {
                        if (item.newMultiple) {
                            // console.log('>>>>>>', item, this.newSelection);
                            this.$nextTick(() => {
                                this.tableData.forEach(val => {
                                    if (item.newMultiple.some(nm => val.pId == nm.pId)) {
                                        this.$refs.multipleTable.toggleRowSelection(val);
                                        // console.log(this.$refs.multipleTable, '99')
                                    }
                                })
                            })
                        }
                    }
                })
                // console.log(this.newSelection, '==========') 
            }).catch(() => {
                this.tableData = []; 
            })
        },
        // 班级
        getClasslist() {
            listClassInfoBySchoolId(this.extendData.schoolId).then(res => {
                this.loading = false;
                this.classList = res.data.content;
                this.classList.forEach((val, index) => {
                    let newObj = {
                        classId: val.pId,
                        className: val.sNickName,
                        newMultiple: []
                    }
                    this.newSelection.push(newObj);
                });
                // console.log(this.newSelection, '1111111111111111');
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.clearData();
        },
        handleClose() {
            this.$refs.ruleForm.resetFields();
            this.clearData();
        },
        // 清空数据
        clearData() {
            this.extendData.dialogExtend = false;
            this.tableData = [];
            this.ruleForm.studentName = '';
            this.ruleForm.phone = '';
            this.ruleForm.pid = '';
            this.leftIndex = null;
            this.timeStatus = '';
        }
    }
}
</script>
<style lang="scss">
    .extend-con{
        ul,li{
            list-style:none;
            margin:0;
            padding: 0;
        }
        .el-dialog {
            width: 1000px;
            .el-dialog__body{
                padding: 25px 20px;
            }
            .el-dialog__footer{
                padding: 0 20px 25px;
            }
        }
        .el-table{
            border: 1px solid rgb(236, 227, 223);
        }
        .extend-class-left{           
            border: 1px solid #ddd;
            border-radius: 2px;
            .extend-title{
                background: #fafafa;
                line-height: 39px;
                font-size: 14px;
                color: #9a9a9a;
                border-bottom: 1px solid #ddd;
                text-indent: 20px;
            }
            >ul{
                height: 280px;
                overflow:auto;
                li{
                    line-height: 38px;
                    text-indent: 12px;
                    cursor: pointer;
                    position: relative;
                    &:hover{
                        background: #f9f9f9;
                    }
                    &.active{
                        background: #f9f9f9;
                    }
                    &.active:after{
                        content: '选择中';
                        line-height: 38px;
                        color: #ff5e2c;
                        position: absolute;
                        right: 8px;
                        font-size: 12px;
                    }
                }
            }
            
        }
    }
</style>
